package cn.zh.stan.activity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import cn.zh.stan.BaseUrl;
import cn.zh.stan.MyApplication;
import cn.zh.stan.R;
import cn.zh.stan.WX.Constants;
import cn.zh.stan.Zf.PayResult;
import cn.zh.stan.util.ToastUtil;
import cn.zh.stan.wxapi.WXPayEntryActivity;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class ReCharge extends BaseActivity {

    ImageView rcback;

    LinearLayout zflin,wxlin;
    ImageView zfimg,wximg;

    Button paybtn;

    MyApplication mapp;
    String uid;

    EditText retxt;
    int type=0;

    IWXAPI msgApi = null;

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                       mapp.setIspay(true);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        mapp.setIspay(false);
                       }
                    Intent intent=new Intent(ReCharge.this, WXPayEntryActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                   }
                default:
                    break;
              }
           };
        };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_re_charge);
        mapp= (MyApplication) getApplication();
        uid=mapp.getSp().getString("uid","");
        msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constants.APP_ID);
        initv();
        }


    public void initv(){
        retxt= (EditText) findViewById(R.id.retxt);
        rcback= (ImageView) findViewById(R.id.rcback);
        zflin= (LinearLayout) findViewById(R.id.zflin);
        wxlin= (LinearLayout) findViewById(R.id.wxlin);
        zfimg= (ImageView) findViewById(R.id.zfimg);
        wximg= (ImageView) findViewById(R.id.wximg);
        paybtn= (Button) findViewById(R.id.paybtn);
        rcback.setOnClickListener(this);
        zflin.setOnClickListener(this);
        wxlin.setOnClickListener(this);
        paybtn.setOnClickListener(this);
        }


    @Override
    public void onClick(View view) {
        super.onClick(view);
       int id=view.getId();
       switch (id){
           case R.id.rcback:
               finish();
               break;
           case R.id.zflin:
                zfimg.setBackgroundResource(R.mipmap.round_check_fill);
                wximg.setBackgroundResource(R.mipmap.round);
                type=0;
                //支付宝
               break;
           case R.id.wxlin:
               zfimg.setBackgroundResource(R.mipmap.round);
               wximg.setBackgroundResource(R.mipmap.round_check_fill);
               //微信
               type=1;
               break;
           case R.id.paybtn:
               //支付
               String mount=retxt.getText().toString();
               if (type==0){
                   //支付宝
                   if (checkAliPayInstalled(ReCharge.this)){
                       getpay(mount);
                   }else {
                     ToastUtil.showShort(ReCharge.this,"请安装支付宝");
                   }
               }else if (type==1){
                   //微信
                   if (isWXAppInstalledAndSupported()){
                       getweix(mount);
                   }else {
                       ToastUtil.showShort(ReCharge.this,"请安装微信");
                   }
                }
               break;
             }
           }


       //支付宝充值
       public void getpay(String mount){
           OkHttpUtils.post(BaseUrl.get_order)
                   .params("userId",uid)
                   .params("totalAmount",mount)
                   .params("subject","充值")
                   .params("body","充值")
                   .execute(new StringCallback() {
                       @Override
                       public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                           try {
                               JSONObject js=new JSONObject(s);
                               boolean State=js.getBoolean("State");
                               if (State){
                                 final String OrderString=js.getString("OrderString");
                                   Runnable payRunnable = new Runnable() {

                                       @Override
                                       public void run() {
                                           PayTask alipay = new PayTask(ReCharge.this);
                                           Map<String, String> result = alipay.payV2(OrderString, true);
                                           Log.i("msp", result.toString());

                                           Message msg = new Message();
                                           msg.what = SDK_PAY_FLAG;
                                           msg.obj = result;
                                           mHandler.sendMessage(msg);
                                          }
                                   };
                                   Thread payThread = new Thread(payRunnable);
                                   payThread.start();

                               }else {
                                   String Msg=js.getString("Msg");
                                   ToastUtil.showLong(ReCharge.this,Msg);
                               }
                           } catch (JSONException e) {
                               e.printStackTrace();
                           }
                          }
                       @Override
                       public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                           super.onError(isFromCache, call, response, e);
                       }
                   });
                  }


   //微信充值
    public void getweix(String mount){
        OkHttpUtils.post(BaseUrl.UnifiedOrder)
                .params("userId",uid)
                .params("money",mount)
                .params("body","充值")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                            boolean Flag=js.getBoolean("Flag");
                            JSONObject Res=js.getJSONObject("Res");
                            String appid=Res.getString("appid");
                            String partnerid=Res.getString("partnerid");
                            String prepayid=Res.getString("prepayid");
                            String noncestr=Res.getString("noncestr");
                            String timestamp=Res.getString("timestamp");
                            String packag=Res.getString("package");
                            String sign=Res.getString("sign");
                              PayReq req = new PayReq();
                                req.appId = appid;
                                req.partnerId  = partnerid;
                                req.prepayId      = prepayid;
                                req.nonceStr   =noncestr;
                                req.timeStamp  = timestamp;
                                req.packageValue  = packag;
                                req.sign=sign;
                                msgApi.sendReq(req);
                                finish();
                            }else {
                                String Msg=js.getString("Msg");
                                ToastUtil.showLong(ReCharge.this,Msg);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                      }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                   });
                }



    public static boolean checkAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
        }

    private boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constants.APP_ID);

        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                && msgApi.isWXAppSupportAPI();

        return sIsWXAppInstalledAndSupported;
      }


     }
